﻿using System;
using System.Windows.Controls;
using System.Windows.Threading;

namespace GEPL.Extensions
{
    /// <summary>
    /// Class containing various extension methods.
    /// </summary>
    public static class ExtensionMethods
    {
        /// <summary>
        /// Returns new instance of type and casts it to other type.
        /// </summary>
        /// <typeparam name="T">Type to which the new instance should be casted (e.g. some interface)</typeparam>
        /// <param name="type">System.Type of object to be created.</param>
        /// <returns>New instance of given type.</returns>
        public static T GetNewInstance<T>(this Type type) where T : class
        {
            var constructor = type.GetConstructor(Type.EmptyTypes);
            if (constructor == null)
                return null;
            var newInstance = constructor.Invoke(null) as T;
            return newInstance;
        }

        /// <summary>
        /// Invokes an action using control's dispatcher.
        /// </summary>
        /// <param name="control">Control on which the action should be invoked.</param>
        /// <param name="callback">Action to invoke.</param>
        public static void Invoke(this Control control, Action callback)
        {
            control.Dispatcher.Invoke(callback, DispatcherPriority.Background);
        }

        /// <summary>
        /// Invokes an action with parameter using control's dispatcher.
        /// </summary>
        /// <typeparam name="T">Type of the parameter.</typeparam>
        /// <param name="control">Control on which the action should be invoked.</param>
        /// <param name="callback">Action to invoke.</param>
        /// <param name="param">An object that should be passed to action as parameter.</param>
        public static void InvokeWithParam<T>(this Control control, Action<T> callback, T param)
        {
            control.Dispatcher.Invoke(() => callback(param), DispatcherPriority.Background);
        }
    }
}